package com.it.schoolbookshop_back.controller.message;

import com.it.schoolbookshop_back.entities.po.Message;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.entities.vo.MessageVO;
import com.it.schoolbookshop_back.service.MessageService;
import com.it.schoolbookshop_back.service.UserService;
import com.it.schoolbookshop_back.utils.Code;
import com.it.schoolbookshop_back.utils.UserContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/messages")
public class MessageController {
    @Autowired
    private MessageService messageService;
    
    @Autowired
    private UserService userService;

    // 发送消息
    @PostMapping("/send")
    public Result<?> sendMessage(@RequestBody Map<String, Object> payload) {
        // 从Token获取当前用户ID，而不是从请求中获取
        Integer senderId = UserContext.getUserId();
        if (senderId == null) {
            return Result.unauthorized();
        }
        
        // 验证接收者ID是否存在
        Integer receiverId = (Integer) payload.get("receiverId");
        if (receiverId == null) {
            return Result.validateFailed("接收者ID不能为空");
        }
        
        // 验证消息内容不为空
        String content = (String) payload.get("content");
        if (content == null || content.trim().isEmpty()) {
            return Result.validateFailed("消息内容不能为空");
        }
        
        // 获取书籍ID（可选）
        Integer bookId = (Integer) payload.get("bookId");
        
        // 验证发送者和接收者用户是否存在
        User sender = userService.getUserById(senderId);
        if (sender == null) {
            return Result.failed(Code.PARAMETER_ERROR, "发送者用户不存在");
        }
        
        User receiver = userService.getUserById(receiverId);
        if (receiver == null) {
            return Result.failed(Code.PARAMETER_ERROR, "接收者用户不存在");
        }
        
        // 不允许给自己发消息
        if (senderId.equals(receiverId)) {
            return Result.validateFailed("不能给自己发送消息");
        }
        
        // 发送消息
        Message savedMessage = messageService.sendMessage(senderId, receiverId, bookId, content);
        
        if (savedMessage != null) {
            return Result.success("消息发送成功");
        } else {
            return Result.failed("消息发送失败");
        }
    }

    // 获取聊天记录
    @GetMapping("/history")
    public Result<?> getHistory(@RequestParam(required = false) Integer userId1, 
                              @RequestParam(required = false) Integer userId2,
                              @RequestParam(required = false) Map<String, Object> params) {
        // 从Token获取当前用户ID
        Integer currentUserId = UserContext.getUserId();
        if (currentUserId == null) {
            return Result.unauthorized();
        }
        
        // 如果传入了params[userId1]和params[userId2]，解析它们
        if (userId1 == null && userId2 == null && params != null) {
            try {
                if (params.containsKey("userId1")) {
                    userId1 = Integer.parseInt(params.get("userId1").toString());
                } else if (params.containsKey("bookId")) {
                    // 如果传递了bookId和sellerId，使用当前用户和sellerId作为聊天用户
                    userId1 = currentUserId;
                    Object sellerId = params.get("sellerId");
                    if (sellerId != null) {
                        userId2 = Integer.parseInt(sellerId.toString());
                    }
                }
            } catch (NumberFormatException e) {
                return Result.validateFailed("无效的用户ID");
            }
        }
        
        // 确保至少有一个用户ID参数
        if (userId1 == null && userId2 == null) {
            return Result.validateFailed("用户ID参数缺失");
        }
        
        // 如果只提供了一个用户ID，使用当前用户ID作为另一个
        if (userId1 == null) {
            userId1 = currentUserId;
        } else if (userId2 == null) {
            userId2 = currentUserId;
        }
        
        // 验证当前用户必须是对话的参与者之一
        if (currentUserId != userId1 && currentUserId != userId2) {
            return Result.failed(403, "无权查看其他用户的聊天记录");
        }
        
        // 使用新的详细信息方法
        List<MessageVO> messages = messageService.getChatHistoryDetail(userId1, userId2, currentUserId);
        return Result.success(messages);
    }
    
    // 获取当前用户的所有聊天列表
    @GetMapping("/chat/list")
    public Result<?> getChatList() {
        // 从Token获取当前用户ID
        Integer currentUserId = UserContext.getUserId();
        if (currentUserId == null) {
            return Result.unauthorized();
        }
        
        // 获取用户聊天列表，确保包含书籍标题信息
        List<Map<String, Object>> chatList = messageService.getUserChatListWithBookInfo(currentUserId);
        return Result.success(chatList);
    }
    
    // 标记消息为已读
    @PutMapping("/read/{messageId}")
    public Result<?> markAsRead(@PathVariable Integer messageId) {
        // 从Token获取当前用户ID
        Integer currentUserId = UserContext.getUserId();
        if (currentUserId == null) {
            return Result.unauthorized();
        }
        
        boolean success = messageService.markMessageAsRead(messageId, currentUserId);
        if (success) {
            return Result.success("标记消息已读成功");
        } else {
            return Result.failed("标记消息已读失败，可能没有权限或消息不存在");
        }
    }
    
    // 标记与特定用户的所有聊天消息为已读
    @PutMapping("/read/chat/{partnerId}")
    public Result<?> markChatAsRead(@PathVariable Integer partnerId) {
        // 从Token获取当前用户ID
        Integer currentUserId = UserContext.getUserId();
        if (currentUserId == null) {
            return Result.unauthorized();
        }
        
        // 验证partnerId是否存在
        if (partnerId == null) {
            return Result.validateFailed("聊天伙伴ID不能为空");
        }
        
        int count = messageService.markAllMessagesAsRead(partnerId, currentUserId);
        return Result.success("已将" + count + "条消息标记为已读");
    }
}
